﻿using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Controls.Primitives;
using Coevery.ViewModel;
using System.Windows.Navigation;
using Coevery.ViewModel.EntityDataService;
using Microsoft.Phone.Shell;

namespace Coevery.PhoneApp
{
    public partial class QuoteDetail : PhoneApplicationPage
    {
        private string _quoteId;
        private Popup _popup;
        private QuoteViewModel _quoteViewModel;

        public QuoteDetail()
        {
            InitializeComponent();
            _quoteViewModel = new QuoteViewModel();
            _quoteViewModel.EnableButton += SetApplicationBarIconButtonEnabled;
            _quoteViewModel.Popup = _popup = new Popup { Child = new PopuWait() };
            DataContext = _quoteViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e) 
        {
          if(e.NavigationMode!=NavigationMode.Back)
          {
              _quoteId = string.Empty;
              if(NavigationContext.QueryString.TryGetValue("Quote",out _quoteId))
              {
                  _quoteViewModel.QuoteId = new Guid(_quoteId);
                  _quoteViewModel.LoadData();
              }
          }

        }

        private void AddComments_Click(object sender, EventArgs e) 
        {
            NavigationService.Navigate(new Uri("/Comment.xaml?Action=Add&ObjectType=Quote&ObjectId=" + _quoteId, UriKind.Relative));
           
        }


        private void EditComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            PhoneApplicationService.Current.State["Note"] = note;

            NavigationService.Navigate(
                new Uri("/Comment.xaml?Action=Edit&ObjectType=Quote&ObjectId=" + _quoteId, UriKind.Relative));
            
        }

        private void DeleteComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            note.IsDeleted = true;
            BaseViewModel.Context.UpdateObject(note);
            BaseViewModel.Context.BeginSaveChanges(OnNodeDeleted, BaseViewModel.Context);
            
        }

        private void OnNodeDeleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() =>
            {
                _popup.IsOpen = true;
                SetApplicationBarIconButtonEnabled(false, null);
                BaseViewModel.Context.EndSaveChanges(result);
                _quoteViewModel.LoadData();
            });
        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            var selectedPivotItem = ctlPanorama.SelectedItem as PivotItem;
            if (selectedPivotItem.Name == "PanDetail")
            {
                _quoteViewModel.LoadData();
            }

            if (selectedPivotItem.Name == "PanComments")
            {
                _quoteViewModel.LoadData();
            }
        }

        public void SetApplicationBarIconButtonEnabled(object sender, EventArgs e)
        {
            foreach (ApplicationBarIconButton item in ApplicationBar.Buttons)
            {
                item.IsEnabled = ((bool?)sender) ?? false;
                
            }
        }

        private void Home_Click(object sender, EventArgs e)
        {
            this.NavigationService.GoBack();
        }

        public void ApplicationBarMenuItem_Click(object sender, EventArgs e) 
        {
            var stageCode = 1;
            var status = "Draft";
            var menuItem = sender as ApplicationBarMenuItem;
            switch(menuItem.Text)
            {
                case "Convert to Delivered":
                    stageCode = 2;
                    status = "Delivered";
                    break;
                case "Convert to Closed Accepted":
                    stageCode = 3;
                    status = " Closed Accepted";
                    break;
                case "Convert to Re-quote":
                    stageCode = 4;
                    status = "Re-quote";
                    break;
                case "Convert to Closed Dead":
                    stageCode = 5;
                    status = "Closed Dead";
                    break;
                case "Convert to Closed Lost":
                    stageCode = 6;
                    status = "Closed Lost";
                    break;
                default:
                    break;
            }
            var result=MessageBox.Show("Are you sure you want to convert the status to "+status+"?","Infomation",MessageBoxButton.OKCancel);
            if(result==MessageBoxResult.OK)
            {
                var currentQuote = _quoteViewModel.Quotes[0];
                currentQuote.StatusCode = stageCode;
                BaseViewModel.Context.UpdateObject(currentQuote);
                BaseViewModel.Context.BeginSaveChanges(OnChangesSaved,BaseViewModel.Context);
            }
        
        }
        private void OnChangesSaved(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() => BaseViewModel.Context.EndSaveChanges(result));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_popup.IsOpen == true)
            {
                _popup.IsOpen = false;
            }
        }
    }
}